<?php
#+------------------------------------------------------------------
#| 普通的。
#+------------------------------------------------------------------
#| Author:Janmas Cromwell <janmas-cromwell@outlook.com>
#+------------------------------------------------------------------
namespace app\library\websocket\tool;

use app\library\websocket\logic\Group;
use app\library\websocket\logic\Messages;
use app\library\websocket\logic\Notice;
use app\library\websocket\logic\Users;
use Swoole\WebSocket\Server;

/**
 * 推送助手
 */
class Pusher
{
	static $instance;

	protected $server;

	protected $from = '';
	protected $sender = [];

	protected $to = '';
	protected $receiver = [];

	protected $toSelf = false;

	protected $needSaveAction = [
		'text', 'image_text', 'image', 'file', 'audio'
	];

	public function __construct(Server $server)
	{
		$this->server = $server;
	}

	public function group(string $chatId)
	{
		$this->to = Group::getUserIdList($chatId);
		$this->receiver = Group::getUserList($chatId);
		return $this;
	}

	public function from(int $fd)
	{
		$this->from = $fd;
		$this->sender = Users::getUserByFd($fd);
		return $this;
	}

	public function toself(int $fd)
	{
		$this->from = $this->to = $fd;
		$this->sender = $this->receiver = Users::getUserByFd($fd);
		return $this;
	}

	public function to(string $userId)
	{
		$this->to = Users::getFd($userId);
		$this->receiver = Users::getUserById($userId);
		return $this;
	}

	public function unicast(Package $package, int $opcode = WEBSOCKET_OPCODE_TEXT, int $flag = SWOOLE_WEBSOCKET_FLAG_FIN)
	{
		if (!boolval($package->isGroup)) {
			if ($this->receiver) {
				if (in_array($package->action, $this->needSaveAction)) {
					echo "{$package->action}类型的消息，需要存储" . PHP_EOL;
					$msgId = Messages::create($package, $this->sender['identity']);
					$message = Messages::get($msgId);
				} else {
					$message = $package->toArray();
				}

				if ($this->server->exists($this->to)) {
					$message['code'] = 200;
					$message['notice'] = 'Success';
					$this->server->push($this->to, json_encode($message, JSON_UNESCAPED_UNICODE), $opcode, $flag);
				}
			} else {
				$builder = new MessageBuilder();
				$builder->write('缺少对方身份信息');
				$this->notice($builder);
			}
		} else {
			echo "这个是单播，但是消息需要的是组播";
		}
	}

	public function multicast(Package $package, int $opcode = WEBSOCKET_OPCODE_TEXT, int $flag = SWOOLE_WEBSOCKET_FLAG_FIN)
	{


	}


	/**
	 * 发送通知
	 * @param MessageBuilder $builder
	 * @param int $opcode
	 * @param int $flag
	 */
	public function notice(MessageBuilder $builder, int $opcode = WEBSOCKET_OPCODE_TEXT, int $flag = SWOOLE_WEBSOCKET_FLAG_FIN)
	{
		if ($this->server->exists($this->from)) {
			$this->server->push($this->from, strval($builder), $opcode, $flag);
			if ($builder->closeClient) {
				$this->server->disconnect($this->from);
			}
			Notice::create($builder, $this->from);
		}
	}
}
